//
//  NeedsJSONResponse.m
//

#import "UsersJSONResponse.h"
#import "Need.h"
#import "JSON/JSON.h"

@implementation UsersJSONResponse

- (NSError*)request:(TTURLRequest*)request processResponse:(NSHTTPURLResponse*)response data:(id)data
{

    NSString *responseBody = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    // Parse the JSON data that we retrieved from the server.
    NSDictionary *json = [responseBody JSONValue];
    [responseBody release];
    
    // Drill down into the JSON object to get the parts
    // that we're actually interested in.
    NSDictionary *root = [json objectForKey:@"rsp"];
  //  totalObjectsAvailableOnServer = [[root objectForKey:@"total"] integerValue];

    // Now wrap the results from the server into a domain-specific object.
    NSDictionary *rawResult = [root objectForKey:@"user"];
	
	User *user = [[[User alloc] init] autorelease];
	
	user._id = [[rawResult objectForKey:@"User"] objectForKey:@"id"];
	user.name = [[rawResult objectForKey:@"User"] objectForKey:@"name"];
	user.lastname = [[rawResult objectForKey:@"User"] objectForKey:@"lastname"];
	user.nickname = [[rawResult objectForKey:@"User"] objectForKey:@"nickname"];
	user.displayname = [[rawResult objectForKey:@"User"] objectForKey:@"displayname"];
	user.biography = [[rawResult objectForKey:@"User"] objectForKey:@"biography"];
	user.pictureurl = [[rawResult objectForKey:@"User"] objectForKey:@"pictureurl"];
	user.lat = [[rawResult objectForKey:@"User"] objectForKey:@"lat"];
	user.lng = [[rawResult objectForKey:@"User"] objectForKey:@"lng"];
	user.whyhelp = [[rawResult objectForKey:@"User"] objectForKey:@"whyhelp"];
	
	
	NSArray *UserNeeds = [rawResult objectForKey:@"UserNeeds"];
	NSMutableArray *Needs = [[NSMutableArray alloc] init];
	
	for (NSDictionary *rawUserNeeds in UserNeeds) {
		
		//	Help *help = [[[Help alloc] init] autorelease];
		Need *need = [[[Need alloc] init] autorelease];		
		need._id = [[rawUserNeeds objectForKey:@"Need"] objectForKey:@"id"];
		need.subject = [[rawUserNeeds objectForKey:@"Need"] objectForKey:@"subject"];
		need.text = [[rawUserNeeds objectForKey:@"Need"] objectForKey:@"text"];
		need.created = [[rawUserNeeds objectForKey:@"Need"] objectForKey:@"created"];
		need.timediff = [[rawUserNeeds objectForKey:@"Need"] objectForKey:@"timediff"];
		need.city = [[rawUserNeeds objectForKey:@"Need"] objectForKey:@"city"];
		need.country = [[rawUserNeeds objectForKey:@"Need"] objectForKey:@"country"];
		need.status = [[rawUserNeeds objectForKey:@"Need"] objectForKey:@"status"];
		need.lat = [[rawUserNeeds objectForKey:@"Need"] objectForKey:@"lat"];
		need.lng = [[rawUserNeeds objectForKey:@"Need"] objectForKey:@"lng"];
		need.helps = [[rawUserNeeds objectForKey:@"Need"] objectForKey:@"helps"];
		
		[Needs addObject:need];
		
	}
	
	user.Needs = Needs;
	
	[self.objects addObject:user];
    
    return nil;
}


- (NSString *)format { return @"json"; }

@end
